package net.tngou.iask.dao;

import java.util.ArrayList;
import java.util.List;

import net.tngou.iask.jdbc.PageUtil;
import net.tngou.iask.jdbc.QueryHelper;
import net.tngou.iask.pojo.Answer;
import net.tngou.iask.pojo.POJO;
import net.tngou.iask.util.IPv4Util;
import net.tngou.iask.util.StringUtil;

/**
 * 选项
 * @author tngou@tngou.net
 *
 */
public class AnswerDao extends BaseDao {

	/**
	 * 取得问题选项
	 * @param page 当前页
	 * @param size 页大小
	 * @param main 实体（）
	 * @param type 类型
	 * @param keyword 搜索关键词
	 * @return
	 */
	public PageUtil getPage(int page,int size,long main,long type,String keyword) {
		List<Answer> list=new ArrayList<>();
		int total=0;
		String sql_r="SELECT *";
		String sql_t="SELECT COUNT(id) ";
		String sql_o=" ORDER BY main DESC,id DESC";//排序
		String sql=" FROM `"+POJO.DABASE+"_answer`";
		if(main!=0)sql=sql+ " WHERE  main IN(0,?) AND type=?";
		else sql=sql+ " WHERE  main=? AND type=?";
		if(StringUtil.isNotEmpty(keyword))
		{
			sql=sql+" AND name LIKE ?";
			
			Object[] params={main,type,"%"+keyword+"%"};
			list=QueryHelper.query_slice(Answer.class, sql_r+sql+sql_o, page, size, params);			
			total=(int) QueryHelper.stat(sql_t+sql, params);
		}else{
			Object[] params={main,type};
			list=QueryHelper.query_slice(Answer.class, sql_r+sql+sql_o, page, size, params);	
			total=(int) QueryHelper.stat(sql_t+sql, params);
		}		
		return new PageUtil(list, page, size, total);
		
	}
	
	/**
	 * 取得问题选项
	 * @param main 实体（）
	 * @param type 类型
	 * @return
	 */
	public List<Answer>  getList(long main,long type) {
		String sql_r="SELECT *";
		String sql_o=" ORDER BY id DESC";//排序
		String sql=" FROM `"+POJO.DABASE+"_answer`";
		if(main!=0)sql=sql+ " WHERE  main IN(0,?) AND type=? ";
		else sql=sql+ " WHERE  main=? AND type=?";
		Object[] params={main,type};
		return QueryHelper.query(Answer.class,sql_r+sql+sql_o,params);
	}
	
	public List<Answer>  getListNotQuestion(long main,long type,long question) {
		String sql_r="SELECT *";
		String sql_o=" ORDER BY id DESC";//排序
		String sql=" FROM `"+POJO.DABASE+"_answer`";
		if(main!=0)sql=sql+ " WHERE  main IN(0,?) AND type=? ";
		else sql=sql+ " WHERE  main=? AND type=?  ";
		sql=sql+"   AND id NOT IN( SELECT answer FROM `iask_question_answer` WHERE question=? )";
		Object[] params={main,type,question};
		return QueryHelper.query(Answer.class,sql_r+sql+sql_o,params);
	}
}
